<template>
  <view>
    <my-modal ref="modal" title="自定义充值">
      <view class="modal-container">
        <view class="form-item">
          <view class="input-title">充值金额</view>
          <view class="input-item">
            <input v-model="rechargeMoney" type="number" class="thorui-input" placeholder="请输入充值金额" placeholder-class="thorui-phcolor" />
          </view>
        </view>
      </view>

      <view class="tui-modalBtn-box">
        <tui-button
          :size="30"
          type="gold"
          width="100%"
          height="80rpx"
          margin="10px 0"
          shape="round"
          :open-type="ifBindTelPhone ? '' : 'getPhoneNumber'"
          @tap="handleSubmitRecharge"
          @getphonenumber="handleSubmitRecharge"
        >
          确认充值
        </tui-button>
      </view>
    </my-modal>

    <!-- 选择房台号组件 -->
    <modal-scan ref="scanModal" showClose></modal-scan>

    <!-- 授权手机号组件 -->
    <modal-get-user-phone ref="getUserPhoneModal"></modal-get-user-phone>

    <my-loading ref="loading"></my-loading>
  </view>
</template>

<script>
import Utils from '@/utils/index'
export default {
  data() {
    return {
      // 传入的参数
      param: null,
      // 充值金额
      rechargeMoney: null,
      // 是否已经授权绑定手机号
      ifBindTelPhone: false
    }
  },
  methods: {
    async open(param) {
      const bid = this.$format(param, 'bid')
      if (!bid) {
        this.$msg('text', '暂未获取到门店号')
        return
      }

      this.param = param
      this.$refs.modal.open({ showClose: this.$format(param, 'showClose', true) })

      // 检查是否绑定手机号
      this.checkTelPhone()
        .then(res => {
          this.ifBindTelPhone = res
          console.log('用户已绑定手机号')
        })
        .catch(err => {
          console.log('用户未绑定手机号')
          this.errMsg(err, '用户未绑定手机号')
        })
    },

    close() {
      this.$refs.modal.close()
      this.rechargeMoney = null
    },

    // 确认充值
    handleSubmitRecharge: Utils.debounce(async function (param) {
      if (this.rechargeMoney > 0) {
        // 如果未绑定手机号，需要调起微信先做授权
        if (!this.ifBindTelPhone) {
          await this.getUserPhone(param)
        }

        this.submitRecharge({ rechargeMoney: this.rechargeMoney, ...this.param })
        return
      }

      return this.$msg('text', '请输入有效的充值金额')
    })
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.tips {
  padding: 10px 10px;
  font-size: $font-size-xs;
  background: #252940;
  margin-bottom: 5px;
}

.tui-modalBtn-box {
  width: calc(100% - 30px);
  margin: 15px auto;
}
</style>
